package com.xhji.spider.controller;

import com.xhji.web.config.redis.RedisExpireAtomicLong;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;

@RestController
public class OrderController implements InitializingBean {

    /**
     * 生成订单id
     */
    private RedisExpireAtomicLong orderIdGenerator;
    @Resource
    private RedisOperations<String, Integer> redisTemplate;

    @RequestMapping("/id")
    public long id(){
        return getOrderId();
    }

    private long getOrderId() {
        LocalDate now = LocalDate.now();
        //自增  一天有效
        long id = orderIdGenerator.increment(1, now.plusDays(1).atStartOfDay().minusSeconds(1));
        return Long.valueOf(now.toString().replaceAll("-", "") + String.format("%07d", id));
    }

    @Override
    public void afterPropertiesSet(){
        orderIdGenerator = new RedisExpireAtomicLong("order-id", redisTemplate);
    }
}
